<template>
  <div class="pane-account">
    <!-- 此处 :model 的作用只是单项数据传递 让 form 组件内部可以获取到 formData 数据 -->
    <el-form label-position="right" label-width="60px" :rules="rules" :model="formData" ref="formRef">
      <el-form-item label="账号" prop="name">
        <!-- 此处的 v-model 的作用是双向数据绑定 -->
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import useLoginStore from '@/store/login/login';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { reactive, ref } from 'vue';
import type { IAccount } from '../types';
import { localCache } from '@/utils/cache';

const ACOUNT_NAME = 'name'
const ACOUNT_PASSWORD = 'password'

const formData = reactive<IAccount>({
  name: localCache.getCache(ACOUNT_NAME) ?? '',
  password: localCache.getCache(ACOUNT_PASSWORD) ?? ''
})
const rules: FormRules<IAccount> = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[A-z0-9]{3,30}$/, message: '必须是3-30位数字或字母组成', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 3, max: 30, message: '请输入3位以上密码' }
  ]
}

const formRef = ref<FormInstance>()
const loginStore = useLoginStore();
function submitForm(isRememberPwd: boolean) {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      // 校验通过，发送网络请求
      await loginStore.loginAccountAction(formData)
      if (isRememberPwd) {
        localCache.setCache(ACOUNT_NAME, formData.name)
        localCache.setCache(ACOUNT_PASSWORD, formData.password)
      } else {
        localCache.deleteCache(ACOUNT_NAME)
        localCache.deleteCache(ACOUNT_PASSWORD)
      }
    } else {
      ElMessage.error('请填写完整登录信息！')
    }
  });
  return formData
}

/**
 * 暴露submitForm函数供外部使用
 * 使用defineExpose宏来定义暴露的函数，使得外部可以访问和调用该函数
 * 这在组件需要从其父组件或另一个外部组件交互时特别有用
 */
defineExpose({
  submitForm
})

</script>
<style scoped lang="less">
.pane-account {}
</style>
